package by.grsu.crs.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import by.grsu.crs.form.SignUpStepOneForm;
import by.grsu.crs.model.User;
import by.grsu.crs.service.AuthenticationService;
import by.grsu.crs.service.impl.AuthenticationServiceImpl;

public class SignUpStepOneAction extends Action {
	private final static String SUCCESS = "success";
    private final static String FAILURE = "failure";
    private final static String CANCEL = "cancel";
    
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {    	
    	SignUpStepOneForm signUpStepOneForm = (SignUpStepOneForm) form;
    	if(isCancelled(request)) {
    		return mapping.findForward(CANCEL);
    	}
    	
    	ActionErrors errors = form.validate(mapping, request);
    	if(!errors.isEmpty()) {
    		saveErrors(request, errors);
    		return mapping.findForward(FAILURE);
    	}
    	
        AuthenticationService authService = new AuthenticationServiceImpl();
        
        User client = authService.signUpStepOne(signUpStepOneForm.getEmail(), signUpStepOneForm.getPassword());        
        if (client != null) {
        	request.getSession().setAttribute("client", client);
        	return mapping.findForward(SUCCESS);
        } else {
            errors.add("email", new ActionMessage("error.email.exists"));
            this.saveErrors(request, errors);
            
            return mapping.findForward(FAILURE);
        }
    }
}
